package vin.pth.example.authrization.config;

import java.util.Collections;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
import pth.authentication.service.AuthenticationUserService;
import vin.pth.authorization.service.AuthorizationUserService;
import vin.pth.base.pojo.DefaultUserDetails;
import vin.pth.base.pojo.GrantedAuthority;
import vin.pth.base.pojo.UserDetails;
import vin.pth.base.service.UserDetailsService;

/**
 * @author Cocoon
 */
@Slf4j
@Configuration
public class SecurityBeanConfig {

  @Resource
  private PasswordEncoder passwordEncoder;

  @Bean
  public AuthorizationUserService authorizationUserService() {
    return userDetails -> {
      log.warn("默认的token为用户名，请根据业务自行实现!");
      return userDetails.getUsername();
    };
  }

  @Bean
  public UserDetailsService userDetailsService() {
    return this::getByUsername;
  }

  public UserDetails testUserDetails() {
    DefaultUserDetails userDetails = new DefaultUserDetails();
    userDetails.setUsername("test");
    userDetails.setPassword(passwordEncoder.encode("test"));
    userDetails.setRoles(Collections.singleton("test"));
    userDetails.setAuthority(Collections.singleton(new GrantedAuthority("*", "/test")));
    userDetails.setUserId(30001);
    return userDetails;
  }

  @Bean
  public AuthenticationUserService authenticationUserService() {
    return this::getByUsername;
  }

  private UserDetails getByUsername(String username) {
    switch (username) {
      case "admin":
        return DefaultUserDetails.adminUser(passwordEncoder.encode(username));
      case "test":
        return testUserDetails();
      default:
        return DefaultUserDetails.anonymousUser();
    }
  }

}
